<template>
  <div ref="chartRef" style="width: 600px; height: 400px;"></div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import * as echarts from 'echarts';
import {appointmentCountByDepartment} from "@/api/appointment.js";

const chartRef = ref(null);
let chartInstance = null;

// 处理后台数据
function processData(originalData) {
  return originalData.map(item => ({
    name: item.departmentName,
    value: item.count
  }));
}

// 图表配置
function getChartOption(chartData) {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: chartData.map(item => item.name)
    },
    series: [
      {
        name: '预约量',
        type: 'pie',
        radius: '55%',
        data: chartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          formatter: '{b}: {c}'
        }
      }
    ]
  };
}

// 初始化图表
const initChart = async () => {
  if (!chartRef.value) return;
  const res = await appointmentCountByDepartment();


  // 模拟后台数据（实际使用时通过props传入）
  const originalData = res.data;

  const chartData = processData(originalData);

  chartInstance = echarts.init(chartRef.value);
  chartInstance.setOption(getChartOption(chartData));
}

// 响应式调整
function resizeChart() {
  chartInstance?.resize();
}

onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  chartInstance?.dispose();
});
</script>
